package quan.dong.handle;

import quan.dong.common.Common;
import quan.dong.common.CommonEnums;
import quan.dong.common.Constant;
import quan.dong.common.TCPSocket;
import quan.dong.object.PriceAlert;
import android.os.Handler;
import android.os.Message;

public class AlertListener implements Runnable {
	Thread runner;
	TCPSocket socket;
	Handler handler;
	String imeiNumber;

	public AlertListener(String imeiNumber, Handler handler, String threadName) {
		super();
		this.imeiNumber = imeiNumber;
		this.handler = handler;
		runner = new Thread(this, threadName);
	}

	public void Start() {
		runner.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		TCPSocket socket = new TCPSocket();
		try {
			boolean isConnected = socket.Create(Constant.SERVER_IP_ADDRESS,
					Constant.PORT);
			if (isConnected) {
				socket.SendExact(Common
						.intToByteArray(CommonEnums.ConnectType.ClientConnect
								.ordinal()));
				byte[] buffer = imeiNumber.getBytes();
				int len = buffer.length;
				socket.SendExact(Common.intToByteArray(len));
				socket.SendExact(buffer);

				while (true) {
					buffer = new byte[4];
					socket.ReadExact(buffer);
					CommonEnums.ConnectType key = CommonEnums.ConnectType
							.values()[Common.byteArrayToInt(buffer)];
					switch (key) {
					case HaveNewAlert:
						buffer = new byte[Constant.SIZE_PRICE_ALERT];
						socket.ReadExact(buffer);
						PriceAlert alert = new PriceAlert();
						alert.Deserialize(buffer);
						Message message = handler.obtainMessage(
								Constant.HANDLER_ALERT, alert);
						handler.sendMessage(message);
						buffer = new byte[1];
						buffer[0] = 1;
						socket.SendExact(buffer);
						break;
					default:
						break;
					}
				}
			}
		} catch (Exception e) {

		}
	}
}
